package net.zjitc.dao.impl;

import net.zjitc.dao.CategoryDao;
import net.zjitc.pojo.Category;
import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by rj1502 on 2017/11/14.
 */
public class CategoryDaoImpl implements CategoryDao {
    public List<Category> findAll() {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from category";
        try {
            List<Category> list = (List<Category>) runner.query(sql,new BeanListHandler(Category.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int insert(Category category) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "insert into category (cname) value(?)";
        try {
            return runner.update(sql,category.getCname());

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int delete(String cid) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql ="delete from category where cid = ?";
        try {
            return  runner.update(sql,cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int update(Category category) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "update category set cname = ? where cid = ?";
        try {
           return runner.update(sql,category.getCname(),category.getCid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Category findByCid(String cid) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql ="select * from category where cid = ?";
        try {
            Category category = (Category) runner.query(sql,new BeanHandler(Category.class),cid);
            return category;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
